﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using myBoard.App.Components.MagnetsStore.ViewsModels;
using myBoard.App.Model;
using myBoard.App.MagnetStore;
using myBoard.App.Business;
using System.IO;
using System.Reflection;
using System.Globalization;
using myBoard.App.Components.MagnetsStore.Controllers;
using myBoard.Framework;

namespace myBoard.App.Components.MagnetsStore.Commands
{
    public class SubmitMagnetCommand : ICommand
    {
        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            Instances instances = new Instances();
            string sessionId = instances.UsersViewModel.ConnectedUserSessionId;
            MagnetViewModel magnetViewModel = parameter as MagnetViewModel;
            
            byte[] magnet=null;
            if (!string.IsNullOrEmpty(magnetViewModel.MagnetPath))
            {
                Assembly assembly = MagnetsManager.GetMagnetAssembly(magnetViewModel.MagnetPath);
                if (assembly!=null)
                {                    
                    Version version = assembly.GetName().Version;
                    magnetViewModel.Version = string.Format("{0}.{1}", version.Major, version.Minor);
                    magnet = Framework.Tools.ConvertFileToByteArray(magnetViewModel.MagnetPath);
                }
                else
                {
                    myBoard.Framework.Forms.MessageBox.Show("Cannot update magnet",
                        string.Format("{0} is not a valid magnet.", Path.GetFileName(magnetViewModel.MagnetPath)),
                        "Magnet Store",
                        System.Diagnostics.EventLogEntryType.Error);
                    return;
                }
            }

            byte[] thumbnail=null;
            if (!string.IsNullOrEmpty(magnetViewModel.ThumbnailPath))
                thumbnail = Framework.Tools.ConvertFileToByteArray(magnetViewModel.ThumbnailPath);

            ArrayOfBase64Binary screenshots = null;
            if (magnetViewModel.ScreenshotsPath !=null && magnetViewModel.ScreenshotsPath.Count > 0)
            {
                screenshots = new ArrayOfBase64Binary();
                foreach (string path in magnetViewModel.ScreenshotsPath)
                {
                    byte[] screenshot = Framework.Tools.ConvertFileToByteArray(path);
                    screenshots.Add(screenshot);
                }
            }

            magnetViewModel.SyncModelWithViewModel();

            MagnetsStoreClient.Client.SubmitMagnetCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(Client_SubmitMagnetCompleted);
            MagnetsStoreClient.Client.SubmitMagnetAsync(sessionId, magnetViewModel._magnet, magnet, thumbnail, screenshots);
            StoreController.UpdateStatus("Submitting magnet ...");
            Mouse.OverrideCursor = Cursors.Wait;            
        }

        void Client_SubmitMagnetCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            StoreController.UpdateStatus("");
            Mouse.OverrideCursor = null;
            if (e.Error != null)
            {
                ExceptionsManager.LogException("Magnets Store", e.Error, true);
            }
            else
            {
                myBoard.Framework.Forms.MessageBox.Show("Submission completed", "Your magnet has been successfully submitted. It will not be available in the store until we validate it. This may take a few days, thank you for your patience.", "Magnets Store", System.Diagnostics.EventLogEntryType.Information, System.Windows.MessageBoxButton.OK);
            }
            MagnetsStoreClient.Client.SubmitMagnetCompleted -= new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(Client_SubmitMagnetCompleted);
        }

        #endregion
    }
}
